import java.util.*;

public class Test {
    public List<String> topKFrequent(String[] words, int k) {
        //统计每一个单词出现的个数
        Map<String,Integer> map = new HashMap<>();
        for (String word: words) {
            if(map.get(word) == null) {
                map.put(word,1);
            }else {
                int val = map.get(word);
                map.put(word,val+1);
            }
        }

        //建立小根堆，传入比较器
        PriorityQueue<Map.Entry<String,Integer>> minHeap = new PriorityQueue<>(new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                if(o1.getValue().compareTo(o2.getValue()) == 0) {
                    return o2.getKey().compareTo(o1.getKey());
                }
                return o1.getValue() - o2.getValue();
            }
        });

        for (Map.Entry<String,Integer> entry: map.entrySet()) {
            if(minHeap.size() < k) {
                minHeap.offer(entry);
            }else {
                 Map.Entry<String,Integer> top = minHeap.peek();
                 //频率相同时，按字典顺序比较
                 if(top.getValue().compareTo(entry.getValue()) == 0) {
                     if(top.getKey().compareTo(entry.getKey()) > 0) {
                         minHeap.poll();
                         minHeap.offer(entry);
                     }
                 }else {
                     if(top.getValue().compareTo(entry.getValue()) < 0) {
                         minHeap.poll();
                         minHeap.offer(entry);
                     }
                 }
            }
        }

        List<String> ret = new ArrayList<>();
        for(int i = 0;i < k;i ++) {
            Map.Entry<String,Integer> entry = minHeap.poll();
            ret.add(entry.getKey());
        }

        Collections.reverse(ret);
        return ret;
    }
}
